package com.foreveredu.propms.web.struts.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.foreveredu.propms.domain.Building;
import com.foreveredu.propms.domain.District;
import com.foreveredu.propms.domain.House;
import com.foreveredu.propms.domain.HouseSource;
import com.foreveredu.propms.domain.HouseType;
import com.foreveredu.propms.domain.Owner;
import com.foreveredu.propms.domain.PageModel;
import com.foreveredu.propms.domain.Role;
import com.foreveredu.propms.domain.SubDistrict;
import com.foreveredu.propms.domain.User;
import com.foreveredu.propms.service.IManagementService;
import com.foreveredu.propms.web.struts.actionform.HouseActionForm;

public class HouseAction extends AbstractBaseDispatchAction {

	private IManagementService managementService = null;

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	// 跳转到房产列表页面
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		HouseActionForm haf = (HouseActionForm) form;
		
		int offset = 0;
		String pageOffset = request.getParameter("pager.offset");// 获得翻页参数，即下一开始的纪录位置
		if (pageOffset != null && !pageOffset.equals("")) {
			offset = Integer.parseInt(pageOffset);
		}
		if (offset < 0) {
			return mapping.findForward("houseList");
		}
	
		// 获取当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal()
				.getUsername());
		} catch(ClassCastException e) {
			//用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		Set<Role> roles = user.getRoles();
		Role role_Admin = managementService.findRoleByName("ADMIN");
		Role role_ChargeMan = managementService.findRoleByName("CHARGEMAN");
		
		int districtId = 0;
		
		List<SubDistrict> subDistrictList = null;
		
		if(roles.contains(role_ChargeMan)) {
			if (haf.getSubDistrict_id() == 0|| "".equals(haf.getSubDistrict_id())) {
				// 获取当前物业管理员所在的物业服务处
				District dis = user.getDistrict();
				districtId = dis.getId();
				subDistrictList = managementService.findSubDistrictsOfDistrict(dis);
				
				PageModel pm = managementService.findHouseList(offset, districtId);
				request.setAttribute("pm", pm);
			}else{
				// 获取当前物业管理员所在的物业服务处
				District dis = user.getDistrict();
				districtId = dis.getId();
				subDistrictList = managementService.findSubDistrictsOfDistrict(dis);
				PageModel pm = managementService.findOwnerListBySubDistrict(offset, haf.getSubDistrict_id());
				SubDistrict subDistrict =managementService.findSubDistrictById(haf.getSubDistrict_id());
				request.setAttribute("subDistrict", subDistrict);
				request.setAttribute("pm", pm);
			}
		}
		if (roles.contains(role_Admin)) {
			if (haf.getSubDistrict_id() == 0|| "".equals(haf.getSubDistrict_id())) {
				subDistrictList = managementService.findSubDistricts();
				PageModel pm = managementService.findHouseList(offset, districtId);
				request.setAttribute("pm", pm);
			}else{
				PageModel pm = managementService.findOwnerListBySubDistrict(offset, haf.getSubDistrict_id());
				subDistrictList = managementService.findSubDistricts();
				SubDistrict subDistrict =managementService.findSubDistrictById(haf.getSubDistrict_id());
				request.setAttribute("subDistrict", subDistrict);
				request.setAttribute("pm", pm);
			}
		}
		
		request.setAttribute("subDistrictList", subDistrictList);
		return mapping.findForward("houseList");
	}

	// 跳转到房产增加操作页面
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 获取当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal()
				.getUsername());
		} catch(ClassCastException e) {
			//用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		Set<Role> roles = user.getRoles();
		Role role_Admin = managementService.findRoleByName("ADMIN");
		Role role_ChargeMan = managementService.findRoleByName("CHARGEMAN");
		
		List<SubDistrict> subDistrictList = null;
		List<District> districtList = null;
		if(roles.contains(role_Admin)) {
			subDistrictList = managementService.findSubDistricts();
			districtList = managementService.findDistricts();
		} else if(roles.contains(role_ChargeMan)) {
			// 获取当前物业管理员所在的物业服务处
			District dis = user.getDistrict();
			districtList = new ArrayList<District>();
			districtList.add(dis);
			
			subDistrictList = managementService.findSubDistrictsOfDistrict(dis);
		}
		
		request.setAttribute("subList", subDistrictList);
		request.setAttribute("districtList", districtList);

		// 获取房产类型列表
		List<HouseType> houseTypeList = managementService.findHouseTypes();
		request.setAttribute("houseTypeList", houseTypeList);

		// 获取房产来源列表
		List<HouseSource> houseSourceList = managementService.findHouseSources();
		request.setAttribute("houseSourceList", houseSourceList);

		return mapping.findForward("toHouseAdd");
	}

	// 完成房产添加操作
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HouseActionForm haf = (HouseActionForm) form;
		
		// 获取当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal()
				.getUsername());
		} catch(ClassCastException e) {
			//用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		Set<Role> roles = user.getRoles();
		Role role_Admin = managementService.findRoleByName("ADMIN");
		Role role_ChargeMan = managementService.findRoleByName("CHARGEMAN");
		
		List<SubDistrict> subDistrictList = null;
		List<District> districtList = null;
		if(roles.contains(role_Admin)) {
			subDistrictList = managementService.findSubDistricts();
			districtList = managementService.findDistricts();
		} else if(roles.contains(role_ChargeMan)) {
			// 获取当前物业管理员所在的物业服务处
			District dis = user.getDistrict();
			districtList = new ArrayList<District>();
			districtList.add(dis);
			
			subDistrictList = managementService.findSubDistrictsOfDistrict(dis);
		}
		
		request.setAttribute("subList", subDistrictList);
		request.setAttribute("districtList", districtList);

		// 获取房产类型列表
		List<HouseType> houseTypeList = managementService.findHouseTypes();
		request.setAttribute("houseTypeList", houseTypeList);

		// 获取房产来源列表
		List<HouseSource> houseSourceList = managementService
				.findHouseSources();
		request.setAttribute("houseSourceList", houseSourceList);
		
	    //表单验证
		if(haf.getHouseId()== null ||"".equals(haf.getHouseId())){
			request.setAttribute("houseIdError", "请输入房产编号");
		    
			return mapping.findForward("toAdd");
		} 
		if(haf.getName() == null || "".equals(haf.getName())){
			request.setAttribute("houseNameError", "请输入房产名称");
			
			return mapping.findForward("toAdd");
		}
		if(haf.getHouseTypeId() == 0){
			request.setAttribute("houseTypeError", "请选择房产类型");
			
			return mapping.findForward("toAdd");
		}
		if(haf.getHouseSourceId() == 0){
			request.setAttribute("houseSourceError", "请选择房产来源");
			
			return mapping.findForward("toAdd");	
		}
		if(haf.getUnit() == 0){
			request.setAttribute("houseUnitError", "请输入房产所处的单元");
			
			return mapping.findForward("toAdd");
		}
		if(haf.getFloor() == 0){
			request.setAttribute("houseFloorError", "请输入所处的楼层");
			
			return mapping.findForward("toAdd");
		}
		
		if(haf.getBuildingId() == 0){
			request.setAttribute("houseBuildingIdError", "请输入所处的楼栋");
			
			return mapping.findForward("toAdd");
		}
		if (haf.getDistrictId() == 0) {
			request.setAttribute("districtIdError", "请选择物业服务处");
			
			return mapping.findForward("toAdd");
		}
		if(haf.getSubId()== 0){
			request.setAttribute("houseSubIdError", "请选择房产所处的小区");
			
			return mapping.findForward("toAdd");
		}
		if(haf.getOwnerName() == null || "".equals(haf.getOwnerName())){
			request.setAttribute("houseOwnerNameError", "请输入业主的姓名");
			
			return mapping.findForward("toAdd");
		}
		
		//将基本类型的表单数据复制到house对象
		House house = new House();
		PropertyUtils.copyProperties(house, haf);
		
		/*
		 * 房产编号应实现自动生成，生成规范为:物业服务处+小区+楼栋号+单元号+房号，
		 * 房号手动输入，房产编号后台自动生成，01 01 01 1 0001 形式。
		 */
		String disNum = managementService.findDistrictById(haf.getDistrictId()).getDistrictId();
		String subNum = managementService.findSubDistrictById(haf.getSubId()).getSubDistrictId();
		String buildingNum = managementService.findBuildingById(haf.getBuildingId()).getBuildingId();
		String houseId = disNum+subNum+buildingNum+haf.getUnit()+haf.getHouseId();
		
		if(managementService.findHouseByHouseId(houseId) != null){
			request.setAttribute("houseIdRequestError", "您输入的房产编号已经存在，请重新输入！");
			
			return mapping.findForward("toAdd");
		}
		
		house.setHouseId(houseId);
		
		//获得房产类型对象
		HouseType type = managementService.findHouseTypeById(haf.getHouseTypeId());
		house.setType(type);
		
		//获得房产来源对象
		HouseSource source = managementService.findHouseSourceById(haf.getHouseSourceId());
		house.setSource(source);
		
		//获得楼栋对象
		Building building = managementService.findBuildingById(haf.getBuildingId());
		house.setBuilding(building);
		
		//判断业主是否已存在，可根据业主身份证号码进行查询，
		//从表单中获取业主的身份证
		if(haf.getIdCard() == null ||"".equals(haf.getIdCard())){
			//业主不存在，则新建该业主
			Owner ownerNew = new Owner();
			PropertyUtils.copyProperties(ownerNew, haf);
			ownerNew.setPassword("123456");
			ownerNew.setName(haf.getOwnerName());
			house.setOwner(ownerNew);
			//设置业主对象的房产
			Set<House> houses = new HashSet<House>();
			ownerNew.setHouses(houses);
			
		}else{
			String cardId = haf.getIdCard();
			//根据身份证查询业主
			Owner owner = managementService.findOwnerByIdCard(cardId);
			if(owner != null){
				//该业主已经存在,设置该房产的业主
				house.setOwner(owner);
				//设置业主对象的房产
				Set<House> houses = new HashSet<House>();
				owner.setHouses(houses);
			} else {
				//业主不存在，则新建该业主
				Owner ownerNew = new Owner();
				PropertyUtils.copyProperties(ownerNew, haf);
				ownerNew.setName(haf.getOwnerName());
				house.setOwner(ownerNew);
				//设置业主对象的房产
				Set<House> houses = new HashSet<House>();
				ownerNew.setHouses(houses);
			}
		}
        
		//保存房产对象
		request.setAttribute("subDistrictId", haf.getSubId());
		managementService.saveHouse(house);

		return mapping.findForward("saveSuccess");
	}

	// 跳转到房产修改页面
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		// 获取当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal()
				.getUsername());
		} catch(ClassCastException e) {
			//用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		Set<Role> roles = user.getRoles();
		Role role_Admin = managementService.findRoleByName("ADMIN");
		Role role_ChargeMan = managementService.findRoleByName("CHARGEMAN");
		
		List<SubDistrict> subDistrictList = null;
		List<District> districtList = null;
		if(roles.contains(role_Admin)) {
			subDistrictList = managementService.findSubDistricts();
			districtList = managementService.findDistricts();
		} else if(roles.contains(role_ChargeMan)) {
			// 获取当前物业管理员所在的物业服务处
			District dis = user.getDistrict();
			districtList = new ArrayList<District>();
			districtList.add(dis);
			
			subDistrictList = managementService.findSubDistrictsOfDistrict(dis);
		}
		
		request.setAttribute("subList", subDistrictList);
		request.setAttribute("districtList", districtList);
        
		// 获得日志记录器
		Logger log = Logger.getLogger(HouseAction.class);

		HouseActionForm bdaf = (HouseActionForm)form;  
        House house = managementService.findHouseById(bdaf.getId());
        log.info("id=" + bdaf.getId());
        
        request.setAttribute("house", house);
        //获取该房产的业主
        Owner owner=house.getOwner();
        request.setAttribute("owner", owner);
        
        // 获取房产类型列表
		List<HouseType> houseTypeList = managementService.findHouseTypes();
		request.setAttribute("houseTypeList", houseTypeList);
		
		//获取房产来源列表
		List<HouseSource> houseSourceList = managementService.findHouseSources();
		request.setAttribute("houseSourceList", houseSourceList);
		
		//获取楼栋 
		List<Building> buildingList = managementService.findBuildingsBySubDistrict(house.getBuilding().getSubDistrict().getId());
		request.setAttribute("houseBuildingList", buildingList);
		
		//将房产的信息保存到表单中（只保存基本数据类型）
		PropertyUtils.copyProperties(bdaf, house);
		
		//获得房产类型对象,也就是将更改后的数据保存在表单中
		bdaf.setHouseTypeId(house.getType().getId());
		
		//获得房产来源对象，也就是将更改后的数据保存在表单中
		bdaf.setHouseSourceId(house.getSource().getId());
		
		//获取房产对应的楼栋对象，也就是将更改后的数据保存在表单中
		bdaf.setBuildingId(house.getBuilding().getId());
		
		return mapping.findForward("houseUpdate");
	}

	// 保存房产修改数据
	public ActionForward updateSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//获得表单的值
        HouseActionForm bdaf = (HouseActionForm)form;
        
       //添加表单验证
//       if(bdaf.getHouseId().equals("")){
//    	   request.setAttribute("houseIdError", "请输入房产编号");
//    	   return mapping.findForward("toUpdate");
//       }
//       if(bdaf.getHouseTypeId() == 0){//没有填写房产类型
//    	   
//    	   request.setAttribute("houseTypeError","请输入房产类型");
//    	   return mapping.findForward("toUpdate");
//       }
//       if(bdaf.getHouseSourceId() == 0){
//    	   request.setAttribute("houseSourceError", "请输入房产来源");
//    	   return mapping.findForward("toUpdate");
//       }
//       if(bdaf.getOwnerName().equals("")){
//    	   request.setAttribute("houseownerError", "请输入业主姓名");
//    	   return mapping.findForward("toUpdate");
//       }
       
        House house = managementService.findHouseById(bdaf.getId());
        
        //将页面中的基本数据类型复制，但是不能复制应用数据类型
        PropertyUtils.copyProperties(house, bdaf);
        
        //设置房产类型
        HouseType houseType = managementService.findHouseTypeById(bdaf.getHouseTypeId());
        house.setType(houseType);
        
        //设置房产来源
        HouseSource houseSource = managementService.findHouseSourceById(bdaf.getHouseSourceId());
        house.setSource(houseSource);
        
        //设置楼栋编号
        Building building = managementService.findBuildingById(bdaf.getBuildingId());
        house.setBuilding(building);
        
        //通过房产获得
        Owner owner = house.getOwner();
        //从表单中读取业主的信息，
        owner.setName(bdaf.getOwnerName());
        owner.setWorkUnit(bdaf.getWorkUnit());
        owner.setIdCard(bdaf.getIdCard());
        owner.setPhone(bdaf.getPhone());
        owner.setFmName(bdaf.getFmName());
        owner.setFmIdCard(bdaf.getFmIdCard());
        owner.setFmPhone(bdaf.getFmPhone());
        
        request.setAttribute("subDistrictId", bdaf.getSubId());
        managementService.updateHouse(house);
        
		return mapping.findForward("updateSuccess");
	}

	// 完成房产删除操作
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//获取表单中的数据
        HouseActionForm haf = (HouseActionForm)form;
        
        House house = managementService.findHouseById(haf.getId());
        request.setAttribute("subDistrictId", house.getBuilding().getSubDistrict().getId());
        
        managementService.deleteHouseById(haf.getId());
		return mapping.findForward("deleteSuccess");
	}
	
}
